<?php
declare(strict_types=1);

namespace App\Wxc\Service;

use App\Wxc\Exceptions\NotFoundShopException;
use App\Wxc\Model\WxcShopInfo;
use App\Wxc\Service\Query\ProductQuery;
use App\Wxc\Service\Query\ShopInfoQuery;
use Deepwell\ChannelsShop\Api\Product\Enums\SkuStatus;
use Deepwell\EasyQuery\Concern\QueryService;
use Mine\Exception\NormalStatusException;

/**
 * 店铺基础信息服务
 * @method null|WxcShopInfo QueryOne(?ShopInfoQuery $input = null)
 */
class WxcShopInfoService
{
    use QueryService;

    public function __construct()
    {
        $this->queryModelClassName = WxcShopInfo::class;
    }

    // 获取店铺详情
    public function detail(WxcShopInfo|int|string $shop): array
    {
        if (!$shop instanceof WxcShopInfo) {
            $get = new ShopInfoQuery();
            $get->shop_id = $shop;
            $shop = $this->queryOne($get);
        }
        if (!$shop) {
            throw new NotFoundShopException();
        }

        // 店铺基础信息
        $data = $shop->only(['shop_id', 'site_id', 'app_id', 'nickname', 'headimg_url', 'subject_type']);

        // 获取商品信息和主营商品类目
        // 商品数量统计
        $productService = container()->get(WxcProductService::class);
        $getProduct = new ProductQuery();
        $getProduct->status = SkuStatus::OnSale;
        $productCount = $productService->getQuery($getProduct)->count();
        $data['product_count'] = $productCount;

        if ($productCount) {
            // 类目
            $getProduct->select('cats_desc');
            $list = $productService->queryList($getProduct);
            // 统计cats_desc的出现次数
            $catsDescCount = [];
            foreach ($list as $product) {
                $catsDesc = $product->cats_desc;
                if (!isset($catsDescCount[$catsDesc])) {
                    $catsDescCount[$catsDesc] = 0;
                }
                $catsDescCount[$catsDesc]++;
            }
            // 将出现次数按照从大到小排序，并获取前三个
            arsort($catsDescCount); // 降序排序
            $topThreeCategories = array_slice($catsDescCount, 0, 3, true); // 获取前三个元素
            // 将出现次数最多的三个设置为主营类目
            $data['main_categories'] = array_keys($topThreeCategories);
        } else {
            $data['main_categories'] = [];
        }

        return $data;
    }
}